<template>
  <div class="bg-white p-3 rounded-lg shadow">
    <h3 class="text-md font-medium mb-2">上传视频</h3>
    
    <div 
      class="flex items-center justify-center w-full"
      @dragover.prevent="isDragging = true"
      @dragleave.prevent="isDragging = false"
      @drop.prevent="handleFileDrop"
    >
      <label 
        class="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed rounded-lg cursor-pointer transition-colors duration-200"
        :class="[isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300 bg-gray-50 hover:bg-gray-100']"
      >
        <div class="flex flex-col items-center justify-center pt-5 pb-6">
          <svg class="w-8 h-8 mb-3" :class="isDragging ? 'text-blue-500' : 'text-gray-500'" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
          </svg>
          <p class="mb-2 text-sm" :class="isDragging ? 'text-blue-500' : 'text-gray-500'">
            <span class="font-semibold">{{ isDragging ? '释放文件' : '点击上传' }}</span> {{ isDragging ? '' : '或拖放' }}
          </p>
          <p class="text-xs" :class="isDragging ? 'text-blue-400' : 'text-gray-500'">支持 MP4, MOV, WEBM 等视频格式</p>
        </div>
        <input id="dropzone-file" type="file" class="hidden" accept="video/*" @change="handleFileChange" />
      </label>
    </div>
    
    <div v-if="store.videoFile" class="mt-2 text-sm text-gray-600">
      已选择: {{ store.videoFile.name }} ({{ formatFileSize(store.videoFile.size) }})
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useVideoStore } from '../stores/videoStore';

// 使用 Pinia store
const store = useVideoStore();

// 定义事件
const emit = defineEmits(['file-selected']);

// 拖放状态
const isDragging = ref(false);

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    processVideoFile(file);
  }
};

// 处理文件拖放
const handleFileDrop = (event) => {
  isDragging.value = false;
  
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('video/')) {
    processVideoFile(file);
  } else {
    alert('请上传视频文件');
  }
};

// 处理视频文件
const processVideoFile = (file) => {
  // 更新 store 中的文件
  store.videoFile = file;
  // 触发事件通知父组件
  emit('file-selected', file);
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>